<?php

namespace App\Services\Message;

use App\Models\Activity\Join as ActivityJoin;
use App\Models\Group\Group;
use App\Models\Group\GroupMembers;
use App\Models\Member\Member;
use App\Models\Posts\Posts;
use App\Models\Store\Store;
use App\Models\Vote\Vote;
use App\Services\Com\UtilService;
use App\Services\Easemob\Groups;
use App\Services\Member\MemberService;
use App\Services\Member\MemberInfoService;
use App\Services\Com\MessageService as ComMessageService;
use App\Jobs\SyncSendMessage;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;

class MessageService
{
    /**
     * 后台消息推送
     * 推送管理
     * 
     * 调用示例
     * $send_info = ['content'=>'系统指定测试', 'jump_type'=>3, 'router'=>'http://migo.com', 'send_type'=>4, 'send_uuid'=>['013dc5b3-39c8-43c7-b942-9d0d00c32724']];
     * \App\Jobs\SyncSendMessage::dispatch($send_info)->onQueue('NotifyUsers');
     * 
     * @param $content 推送文案
     * @param $jump_type 跳转类型： 1:不跳转、2:跳转到内部模块（选择跳转模块：新闻、活动、动态、店铺、个人圈子、学校）、3:跳转H5
     * @param $router 填写跳转参数
     * @param $send_type 1:全部、 2:学校（可搜索）、 3:性别、 4:活动（可搜索）、 5指定uuid用户
     * @param $send_uuid 1:传空，2 学校uuid 数组，3性别：1男 2女,  4 活动uuid 5 用户uuid
     * @return array
     */
    public static function assignSendMessage(string $content = '', int $jump_type = 0, string $router = '',  
        int $send_type = 0, array $send_uuid = [], string $title = '系统消息', int $type = 114)
    {
        $param['type'] = $type;
        $param['place'] = '';
        $param['service_type'] = '';
        $param['service_uuid'] = '';
        $param['title'] = $title;
        $param['all_context'] = $content;
        $param['owner_uuid'] = '';
        $param['route_link'] = $router;
        try {
        
            if($send_type == 1){
                // 全部用户
                $send_member = Member::get();
            }elseif($send_type == 2){
                //指定学校
                $send_member = Member::wherein('school_uuid',$send_uuid)->get();
            }elseif($send_type == 3){
                // 性别
                $send_member = Member::whereIn('sex',$send_uuid)->get();
            }elseif($send_type == 4){
                // 活动
                $send_member = ActivityJoin::wherein('activity_uuid',$send_uuid)->get();
            }elseif($send_type == 5){
                // 指定uuid用户
                $send_member = Member::wherein('uuid',$send_uuid)->get();
            }
            $sned_members_info = [];
            $members_uuid = [];
            foreach ($send_member as $key => $value) {
                $members_uuid[] = $value['uuid'];
            }
            ComMessageService::sendMessage($param, $members_uuid, $sned_members_info);
        } catch (\Exception $e) {
            Log::alert($e->getMessage());
//            throw new \Exception($e->getMessage());
        }
    }

    /**
     * @param $param
     * @return array
     * 处理list数据
     */
    public static function doListData($attentions_maps, $myAttentionsMaps, $fansMaps, $memberMaps, &$list, $onlineMaps = [], $usersTrendsMap = [])
    {
        $memberInfo = $memberMaps[$list['send_member_uuid']] ?? [];

        $list['im_username']  = UtilService::memberUuidToImAccount($memberInfo['uuid'] ?? '');//用户名
        $list['username']     = $memberInfo['nickname'] ?? null;//发送者昵称
        $list['title']        = $memberInfo['title'] ?? null;//发送者圈子名称
        $list['avatar']       = $memberInfo['avatar_url'] ?? null;//发送者头像
        $list['state']        = $memberInfo['state'] ?? null;//发送者state
        $list['online']       = isset($onlineMaps[$list['send_member_uuid']]) ? 1 : 0;//1在线0不在线
        $list['country']      = $memberInfo['country']['code'] ?? null;//国家代码
        $list['country_name'] = $memberInfo['country']['name'] ?? null;//国家名称
        $list['country_flag'] = $memberInfo['country']['nationalflag'] ?? null;//国家旗帜

        $list['attention']              = isset($attentions_maps[$list['send_member_uuid']]) ? 1 : 0;//1是已经关注0，是未关注
        $list['my_attention']           = isset($myAttentionsMaps[$list['send_member_uuid']]) ? 1 : 0;//1是已经关注给我打招呼的人 0，是未关注给我打招呼的人
        $list['fans_count']             = $fansMaps[$list['send_member_uuid']] ?? 0;//粉丝数
        $list['circles_title']          = $memberInfo['title'] ?? null;//圈子名称
        $list['circles_background_url'] = $memberInfo['circles_background_url'] ?? null;//圈子背景图地址
        $list['school']                 = $memberInfo['school'] ?? null;//学校名
        $list['trends']                 = $usersTrendsMap[$list['send_member_uuid']] ?? 0;//动态数
        $list['activity_count']         = 1000;//活跃度 todo
        $list['vip']                    = 0;//vip
        $list['sex']                    = $memberInfo['sex'] ?? '';//性别  1男 2女 0未知
        $list['year_of_birth']          = MemberInfoService::yearOfBirth($memberInfo['birthday'] ?? '');//出生年份
        $list['works']                  = $memberInfo['works'] ?? [];//工作经历
        
    }


    public static function getMessageRelationData($memberUuid, $memberUuids)
    {
        //批量粉丝
        $fansCounts = MemberService::batchFollowCount($memberUuids);
        $fansMaps   = [];
        if (!empty($fansCounts)) {
            $fansMaps = array_column($fansCounts, 'nums', 'followed_member_uuid');
        }
        //某人的关注批量
        $attentions      = MemberService::batchAttention($memberUuid, $memberUuids);
        $attentions_maps = [];
        if (!empty($attentions)) {
            $attentions_maps = array_column($attentions, 'followed_member_uuid', 'followed_member_uuid');
        }

        //批量是否关注我
        $myAttentions     = MemberService::batchAttentionMe($memberUuid, $memberUuids);

        $myAttentionsMaps = [];
        if (!empty($myAttentions)) {
            // $myAttentionsMaps = array_flip($myAttentions);
            $myAttentionsMaps = $myAttentions;
        }
        //批量在线
        $onlineMaps     = MemberService::onlineUsersMtl($memberUuids);

        //批量动态
        $usersTrendsMap = MemberService::usersTrendsMtl($memberUuids);        

        // 获取当前消息对应人的内容信息
        $rowObj     = Member::select(['id', 'uuid', 'mobile_prefix', 'mobile', 'email', 'no', 'avatar_url', 'created_at', 'name', 'sex', 'nickname',
            'birthday', 'enabled', 'state', 'country_uuid', 'school_uuid', 'title', 'background_url as circles_background_url', 'desc as circles_desc'])
            ->with([
                'school' => function ($query) {
                    $query->select(['uuid', 'name', 'cn_name', 'state']);
                }
            ])
            ->with([
                'country' => function ($query) {
                    $query->select(['uuid', 'name', 'mobile_prefix', 'nationalflag', 'code']);
                }
            ])
            ->with([
                'works'=>function($query){
                    $query->select(['*']);
                }
            ])
            //->where($where)
            ->whereIn('uuid', $memberUuids)
            ->get();

        $row_obj_arr = $rowObj->toArray();
        
        $memberMaps = [];
        if (!empty($row_obj_arr)) {
            $memberMaps = array_column($row_obj_arr, null, 'uuid');
        }
        return [$attentions_maps, $myAttentionsMaps, $fansMaps, $memberMaps, $onlineMaps, $usersTrendsMap];
    }

}
